package com.aye.haze_detection;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.ServiceSettings;
import com.google.gson.Gson;
import com.qweather.plugin.view.QWeatherConfig;
import com.qweather.sdk.bean.air.AirNowBean;
import com.qweather.sdk.bean.base.Code;
import com.qweather.sdk.bean.base.Lang;
import com.qweather.sdk.bean.base.Range;
import com.qweather.sdk.bean.base.Unit;
import com.qweather.sdk.bean.geo.GeoBean;
import com.qweather.sdk.bean.weather.WeatherNowBean;
import com.qweather.sdk.view.HeConfig;
import com.qweather.sdk.view.QWeather;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


public class MainActivity extends AppCompatActivity {
    private static final String TAG = MainActivity.class.getSimpleName();
    String Country=null;
    String Province=null;
    String City=null;
    String Street=null;
    String CityId=null;
    String Weather=null;
    double Longitude,Latitude;
    TextView text_location;
    TextView text_weather;
    TextView text_tips;
    Button button_location;
    Button button_toMap;
    Button button_weather;
    List<GeoBean.LocationBean> CityBean;
    String AirLevel,AirCategory,AirAqi,AirPM10,AirPM25;


    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    //定位成功回调信息，设置相关消息

                    Country = amapLocation.getCountry();
                    Province = amapLocation.getProvince();
                    City = amapLocation.getCity();
                    Street = amapLocation.getStreet();
                    Longitude = amapLocation.getLongitude();//获取经度
                    Latitude = amapLocation.getLatitude();//获取纬度


                    QWeather.getGeoCityLookup(MainActivity.this, City, new QWeather.OnResultGeoListener() {
                        @Override
                        public void onError(Throwable throwable) {
                            Log.i(TAG, "getGeoCityLookup onError: " + throwable);
                        }

                        @Override
                        public void onSuccess(GeoBean geoBean) {
                            Log.i(TAG, "getGeoCityLookup onSuccess: " + new Gson().toJson(geoBean));
                            //先判断返回的status是否正确，当status正确时获取数据，若status不正确，可查看status对应的Code值找到原因
                            if (Code.OK == geoBean.getCode()) {
                                CityBean = geoBean.getLocationBean();
                                CityId = CityBean.get(1).getId();
//                               Log.d(TAG, "ID " + CityId);
                            } else {
                                //在此查看返回数据失败的原因
                                Code code = geoBean.getCode();
                                Log.i(TAG, "failed code: " + code);
                            }
                        }
                    });

                    /**
                     * 实况天气数据
                     * @param location 所查询的地区，可通过该地区ID、经纬度进行查询经纬度格式：经度,纬度
                     *                 （英文,分隔，十进制格式，北纬东经为正，南纬西经为负)
                     * @param lang     (选填)多语言，可以不使用该参数，默认为简体中文
                     * @param unit     (选填)单位选择，公制（m）或英制（i），默认为公制单位
                     * @param listener 网络访问结果回调
                     */
                    QWeather.getWeatherNow(MainActivity.this, CityId, Lang.ZH_HANS, Unit.METRIC, new QWeather.OnResultWeatherNowListener() {
                        @Override
                        public void onError(Throwable e) {
                            Log.i(TAG, "getWeather onError: " + e);
                        }

                        @Override
                        public void onSuccess(WeatherNowBean weatherBean) {
                            Log.i(TAG, "getWeather onSuccess: " + new Gson().toJson(weatherBean));
                            //先判断返回的status是否正确，当status正确时获取数据，若status不正确，可查看status对应的Code值找到原因
                            if (Code.OK == weatherBean.getCode()) {
                                WeatherNowBean.NowBaseBean now = weatherBean.getNow();
                                Weather = now.getText();
                            } else {
                                //在此查看返回数据失败的原因
                                Code code = weatherBean.getCode();
                                Log.i(TAG, "failed code: " + code);
                            }
                        }
                    });

                    Log.d(TAG, "onLocationChanged: "+City+Street);

                    QWeather.getAirNow(MainActivity.this, CityId, Lang.ZH_HANS, new QWeather.OnResultAirNowListener() {
                        @Override
                        public void onError(Throwable throwable) {
                            Log.i(TAG, "getAirNow onError: " + throwable);
                        }

                        @Override
                        public void onSuccess(AirNowBean airNowBean) {
                            Log.i(TAG, "AirNowBean onSuccess: " + new Gson().toJson(airNowBean));
                            //先判断返回的status是否正确，当status正确时获取数据，若status不正确，可查看status对应的Code值找到原因
                            if (Code.OK == airNowBean.getCode()) {
                                AirNowBean.NowBean now = airNowBean.getNow();
                                AirAqi = now.getAqi();
                                AirLevel = now.getLevel();
                                AirCategory = now.getCategory();
                                AirPM10 = now.getPm10();
                                AirPM25 = now.getPm2p5();
                                Log.d(TAG, "getAirNow: "+AirAqi+AirLevel+AirCategory+AirPM10+AirPM25);
                            } else {
                                //在此查看返回数据失败的原因
                                Code code = airNowBean.getCode();
                                Log.i(TAG, "failed code: " + code);
                            }
                        }

                    });



                } else {
                    //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                    Log.e(TAG,"location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
            }

            //动态显示
            if (City != null&&Street != null) {
                text_location.setText("当前定位为："+Country+Province+City+Street);
                Log.d(TAG, "onID "+CityId);
                text_weather.setText("实况天气： "+Weather+"\n空气质量指数为："+AirAqi+"\n空气等级为："+AirLevel+"\n空气质量为："+AirCategory+"\nPM10为: "+AirPM10+"    PM2.5为: "+AirPM25);
                Log.d(TAG, "Air: "+AirLevel+AirCategory);
                if (AirLevel.equals("1")||AirLevel.equals("2")){
                    text_tips.setText("出行提示：今天适合户外呼吸新鲜空气。");
                }else if (AirLevel.equals("3")||AirLevel.equals("4")){
                    text_tips.setText("出行提示：空气污染，出行请做好防护措施。");
                }else{
                    text_tips.setText("出行提示：空气污染较为严重，请谨慎出行。");
                }
            }


        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button_location = findViewById(R.id.button_location);
        text_location = findViewById(R.id.text_location);
        text_weather = findViewById(R.id.text_weather);
        text_tips = findViewById(R.id.text_tips);
        button_weather = findViewById(R.id.button_weather);


        ServiceSettings.updatePrivacyShow(this,true,true);
        ServiceSettings.updatePrivacyAgree(this,true);

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            //申请WRITE_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE},
                    0);//自定义的code
        }

//初始化定位
        try {
            mLocationClient = new AMapLocationClient(getApplicationContext());
        } catch (Exception e) {
            e.printStackTrace();
        }
//设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
//初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();

        AMapLocationClientOption option = new AMapLocationClientOption();
        /**
         * 设置定位场景，目前支持三种场景（签到、出行、运动，默认无场景）
         */
        option.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.Transport);
        if(null != mLocationClient){
            mLocationClient.setLocationOption(option);
            //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
            mLocationClient.stopLocation();
            mLocationClient.startLocation();
        }
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//获取一次定位结果：
//该方法默认为false。
        mLocationOption.setOnceLocation(false);

//获取最近3s内精度最高的一次定位结果：
//设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
        mLocationOption.setOnceLocationLatest(true);

//设置定位间隔,单位毫秒,默认为2000ms，最低1000ms。
        mLocationOption.setInterval(1000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //开始定位
        mLocationClient.startLocation();


      //和风天气
        HeConfig.init("HE2205062011141016", "f667aece7e3146fc90d441a825ad8fe4");
        //切换至开发版服务
        HeConfig.switchToDevService();

//        QWeatherConfig.init("f667aece7e3146fc90d441a825ad8fe4",City);

        //查询

        //启动服务
        Intent intent2Service = new Intent(this,MyService.class);
        startService(intent2Service);





        button_toMap = findViewById(R.id.go2map);
        button_toMap.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this,MapActivity.class));
            }
        });


        button_location.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mLocationClient.startLocation();
                intent2Service.putExtra("city",City);
                intent2Service.putExtra("cityid",CityId);
                intent2Service.putExtra("weather",Weather);
                intent2Service.putExtra("airaqi",AirAqi);
                startService(intent2Service);
               if (City != null&&Street != null) {
                   Toast.makeText(MainActivity.this,"定位成功！",Toast.LENGTH_SHORT).show();
                   text_location.setText("当前定位为："+Country+Province+City+Street);
                   Log.d(TAG, "onID "+CityId);
                   text_weather.setText("实况天气： "+Weather+"\n空气质量指数为："+AirAqi+"\n空气等级为："+AirLevel+"\n空气质量为："+AirCategory+"\nPM10为: "+AirPM10+"      PM2.5为: "+AirPM25);
                   Log.d(TAG, "Air: "+AirLevel+AirCategory);
                   if (AirLevel.equals("1")||AirLevel.equals("2")){
                   text_tips.setText("出行提示：今天适合户外呼吸新鲜空气。");
                   }else if (AirLevel.equals("3")||AirLevel.equals("4")){
                       text_tips.setText("出行提示：空气污染，出行请做好防护措施。");
                   }else{
                       text_tips.setText("出行提示：空气污染较为严重，请谨慎出行。");
                   }


               }
            }
        });


        button_weather.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent2Weather = new Intent(MainActivity.this,WeatherActivity.class);
                intent2Weather.putExtra("cityid",CityId);
                startActivity(intent2Weather);
            }
        });



    }



}

